import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { Session } from '/@/utils/storage';
import {useLoginApi} from "/@/api/login";
// 引入 api 请求接口
const useLogin = useLoginApi();

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: () => ({
		userInfos: {
			userName: '',
			photo: '',
			time: 0,
			roles: [],
			authBtnList: [],
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			} else {
				const userInfos = await this.getApiUserInfo();
				this.userInfos = userInfos;
			}
		},
		// 模拟接口数据
		// https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
		async getApiUserInfo() {
			const userName = Cookies.get('userName');
			const { data } = await useLogin.getUserInfo(Session.get('token'))
			// 模拟数据，请求接口时，记得删除多余代码及对应依赖的引入
			if(data && data.name && Array.isArray(data.permissions)){
				let { permissions, name, avatar } = data
				return new Promise((resolve) => {
					setTimeout(() => {
						const permissionsForStr = permissions.map(num=>num.toString());
						// 用户信息模拟数据
						const userInfos = {
							userName: userName,
							photo:avatar,
							time: new Date().getTime(),
							roles: permissionsForStr,
							authBtnList: permissionsForStr,
						};
						Session.set('userInfo', userInfos);
						resolve(userInfos);
					}, 0);
				});
			}else{
				return new Promise((resolve) => {
					setTimeout(() => {
						const userInfos = {userName: userName, photo:'', time: new Date().getTime(), roles: [], authBtnList: []};
						resolve(userInfos);
					}, 0)
				})
			}
		},
	},
});
